var locationData = require('../../../staticData/locationKeyValue.json');
exports.followUpCustomers = (req, res) => {

    var restfulParams = req.routeInfo.restfulParams;

    var resultData = {};

    var u_id = restfulParams.u_id;

    var is_manager = restfulParams.is_manager;//是否是管理 0-否 1-是

    var skip = restfulParams.skip == undefined ? 0 : restfulParams.skip;

    var limit = restfulParams.limit == undefined ? 20 : restfulParams.limit;

    var u_type = restfulParams.u_type;

    var u_osid = restfulParams.os_id;

    var c_uid_condition = '';

    var salesArr = [];

    var userInStr = "";

    var flowingCustomers = 0;

    //查询员工
    function salesSearch(cb) {
        if (is_manager == 1 && (u_type == 1 || u_type == 2)) {

            //战略  查询战略伙伴下所有销售
            console.log("战略 || 代理");
            R.SEND_HTTP(
                req,
                res, {
                    url: CORE_APIConfig.coreAPI.userSearch.Request_Api_Url + "/u_master_osid/" + u_osid,
                    method: 'POST',
                    data: {
                        fields: ['u_id'].join(",")
                    }
                },
                function (data) {

                    salesArr = data.result.data;

                    cb();

                }
            )
        } else if (is_manager == 1 && u_type == 3) {
            //销售主管  查询该销售主管下所有销售.包括自己。
            console.log("销售组长");
            R.SEND_HTTP(
                req,
                res, {
                    url: CORE_APIConfig.coreAPI.userSearch.Request_Api_Url + "/u_leader/" + restfulParams.u_id,
                    method: 'POST',
                    data: {
                        fields: ['u_id'].join(",")
                    }
                },
                function (data) {

                    salesArr = data.result.data;

                    cb();

                }
            )
        } else if (is_manager == 0 && u_type == 3) {
            //普通销售
            console.log("普通销售");
            salesArr.push({
                u_id: u_id
            });
            cb();
        } else if (u_type == 0) {
            //超管
            console.log("超管");
            R.SEND_HTTP(
                req,
                res, {
                    url: CORE_APIConfig.coreAPI.userSearch.Request_Api_Url,
                    method: 'POST',
                    data: {
                        fields: ['u_id'].join(",")
                    }
                },
                function (data) {

                    salesArr = data.result.data;
                    cb();

                }
            )
        }
    }

    // 拼接in语句查询条件
    function fixInCondition(cb) {
        for (var i = 0; i < salesArr.length; i++) {
            userInStr += salesArr[i].u_id + ","
        }
        userInStr = userInStr.substring(0, userInStr.length - 1);
        if (userInStr == '') {
            userInStr = "null";
        }
        if (u_type > 0) {
            c_uid_condition = "/in/c_uid-" + userInStr;
        }

        cb()
    }

    //查询待跟进客户名称，电话，省市区+详细地址，跟进状态，客户评定
    function searchWaitForFlowing(cb) {

        R.SEND_HTTP(
            req,
            res,
            {
                url: CORE_APIConfig.coreAPI.artCustomerSearch.Request_Api_Url + "/c_follow_status/0/c_is_delete/0" + c_uid_condition,
                method: 'POST',
                data: {
                    fields: ['c_id', "c_phone", 'c_create_time', "c_name", "c_campus_name", "c_provinces", "c_city", "c_area", "c_address", "c_follow_status", "c_evaluation"].join(",")
                }
            },
            function (data) {

                resultData.waitForFlowingCustomers = data.result.data;

                for (var i = 0; i < data.result.data.length; i++) {
                    var provinceId = data.result.data[i].c_provinces;
                    var cityId = data.result.data[i].c_city;
                    var areaId = data.result.data[i].c_area;
                    resultData.waitForFlowingCustomers[i].provinceName = locationData[provinceId];
                    resultData.waitForFlowingCustomers[i].cityName = locationData[cityId];
                    resultData.waitForFlowingCustomers[i].areaName = locationData[areaId];
                }

                cb();

            }
        )
    }

    //查询跟进中客户名称，电话，省市区+详细地址，跟进状态，客户评定
    function searchForFlowingCustomer(cb) {

        R.SEND_HTTP(
            req,
            res,
            {
                url: CORE_APIConfig.coreAPI.artCustomerSearch.Request_Api_Url + "/c_follow_status/1/c_is_delete/0" + c_uid_condition,
                method: 'POST',
                data: {
                    fields: ['c_id', "c_phone", 'c_create_time', "c_name", "c_campus_name", "c_provinces", "c_city", "c_area", "c_address", "c_follow_status", "c_evaluation"].join(",")
                }
            },
            function (data) {

                flowingCustomers = data.result.data;

                for (var i = 0; i < data.result.data.length; i++) {
                    var provinceId = data.result.data[i].c_provinces;
                    var cityId = data.result.data[i].c_city;
                    var areaId = data.result.data[i].c_area;
                    flowingCustomers[i].provinceName = locationData[provinceId];
                    flowingCustomers[i].cityName = locationData[cityId];
                    flowingCustomers[i].areaName = locationData[areaId];
                }

                console.log(flowingCustomers)

                cb();

            }
        )
    }

    //查询每个跟进中客户的最后一条跟进记录
    function searchLastFollowUpRecordOfEachCustomers(cb) {
        // ParallelEach SerialEach
        F.ParallelEach(flowingCustomers, function (item, index, callback) {

            //获取该代理下所有销售的订单数据
            R.SEND_HTTP(
                req,
                res,
                {
                    url: CORE_APIConfig.coreAPI.artCustomerFollowRecordSearch.Request_Api_Url + "/cfr_is_delete/0/cfr_cid/" + item.c_id + "/sort_order/cfr_id-desc/skip/0/limit/1",
                    method: 'POST',
                    data: {
                        fields: ['cfr_cid', 'cfr_next_time'].join(',')
                    }
                },
                function (data) {
                    console.log(item.c_id + "的最后一条跟进记录")
                    console.log(data.result.data)

                    var isNextFollow = data.result.data;
                    var nowTime = common.nowTime(false);
                    if (isNextFollow.length > 0) {
                        if(isNextFollow[0].cfr_next_time != 0){
                            console.log("下次跟进时间 < 当前时间？");
                            console.log(parseInt(isNextFollow[0].cfr_next_time)+"<" +nowTime+"??");
                            console.log("下次跟进时间 < 当前时间？");
                            console.log(parseInt(isNextFollow[0].cfr_next_time) < nowTime);
                            if (parseInt(isNextFollow[0].cfr_next_time) < nowTime) {
                                console.log("写入json数组中");
                                resultData.waitForFlowingCustomers.push(item)
                            }
                            callback()
                        }else{
                            callback();
                        }
                    }else{
                        callback();
                    }
                }
            )
        }, cb)
    }


    F.Serial([
        salesSearch,
        fixInCondition,
        searchWaitForFlowing,
        searchForFlowingCustomer,
        searchLastFollowUpRecordOfEachCustomers,
    ], () => {
        RES.successResponse(res, resultData);
    })


}